package com.gurun.codes.business.home;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.gurun.base.DebounceObservableTransformer;
import com.gurun.base.Logger;
import com.gurun.base.utils.CommonUtils;
import com.gurun.base.utils.ToastManager;
import com.gurun.camera.account.activity.AccountUtil;
import com.gurun.camera.device.VideoActivity;
import com.gurun.camera.device.util.DateTimeUtil;
import com.gurun.codes.App;
import com.gurun.codes.R;
import com.gurun.codes.base.BaseAppCompatActivity;
import com.gurun.codes.business.common_alarm.CommonAlarmActivity;
import com.gurun.codes.business.curtain.CurtainActivity;
import com.gurun.codes.business.door_window.DoorWindowActivity;
import com.gurun.codes.business.human_body.HumanBodyActivity;
import com.gurun.codes.business.jpush.JpushContract;
import com.gurun.codes.business.natural_gas.NaturalGasActivity;
import com.gurun.codes.business.setting.SettingActivity;
import com.gurun.codes.business.smog.SmogActivity;
import com.gurun.codes.business.temperature_humidity.TemperatureHumidityActivity;
import com.gurun.codes.business.water.WaterEnterActivity;
import com.gurun.codes.databinding.ActivityMainTwoBinding;
import com.gurun.codes.databinding.PopupHomeListBinding;
import com.gurun.codes.utils.DateTimeUtils;
import com.gurun.codes.utils.ScreenUtils;
import com.gurun.gateway.MainService;
import com.gurun.model.bean.common.DateTimeModel;
import com.gurun.model.bean.event_bean.LoginSuccessEvent;
import com.gurun.model.bean.home.DeviceStatusUpdateModel;
import com.gurun.model.bean.home.GetHomeListResultBean;
import com.gurun.model.bean.home.GetRoomDeviceListResultBean;
import com.gurun.model.bean.home.GetRoomListResultBean;
import com.gurun.model.bean.home.GetTaskListResultBean;
import com.gurun.model.bean.home.GetWeatherByIpResultBean;
import com.jakewharton.rxbinding2.view.RxView;
import com.zyyoona7.lib.EasyPopup;
import com.zyyoona7.lib.HorizontalGravity;
import com.zyyoona7.lib.VerticalGravity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import app.com.tvrecyclerview.ModuleLayoutManager;
import app.com.tvrecyclerview.TvRecyclerView;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.functions.Consumer;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 根据服务器数据动态展示item个数
 */
public class MainActivityTwo extends BaseAppCompatActivity implements MainActivityContract.MainActivityView, JpushContract.JpushView {

    private ActivityMainTwoBinding mBinding;
    private MainActivityContract.MainActivityViewPresenter mPresenter;
    private JpushContract.JpushPresenter mJpushPresenter;
    private List<GetHomeListResultBean.SmartHomeListBean> mHomeListDatas;
    private EasyPopup mHomelistPopupWindow;
    private Items mContentDatas = new Items();
    private MultiTypeAdapter mContentAdapter;
    private Items mRoomDatas = new Items();
    private MultiTypeAdapter mRoomAdapter;
    private MultiTypeAdapter mSceneAdapter;
    private Items mTaskDatas = new Items();
    private MultiTypeAdapter mCommonAdapter;
    private Items mCommonDatas = new Items();
    private int mCurrentHomeId = 0;
    private String mCurrentRoomName = "";

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MainActivityTwo.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main_two);
        mPresenter = new MainActivityContract.MainActivityViewPresenter(this);
        mPresenter.bind(this);
        mJpushPresenter = new JpushContract.JpushPresenter(this);
        mJpushPresenter.bind(this);
        initView();
        initDatas();
        initEvent();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        //绑定push id到服务器
        mJpushPresenter.bindUserPushChannelIdToServer();
        //摄像头云平台
        AccountUtil.getInstance(this).login();
        AccountUtil.getInstance(this).getCountryCode();
        Logger.d("jpush id:" + JPushInterface.getRegistrationID(mContext));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (mPresenter != null) {
            mPresenter.unbind();
        }
        if (mJpushPresenter != null) {
            mJpushPresenter.unbind();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPresenter != null) {
            mPresenter.startUpdateTime();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPresenter != null) {
            mPresenter.stopUpdateTime();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccess(LoginSuccessEvent event) {
        mPresenter.getHomeList();
        mPresenter.getWeatherByIp();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceStatusChanged(DeviceStatusUpdateModel event) {
        if (event != null) {
            int deviceId = event.getDeviceId();
            for (int i = 0; i < mContentDatas.size(); i++) {
                Object item = mContentDatas.get(i);
                if (item instanceof GetRoomDeviceListResultBean.FamilyDevice) {
                    if (((GetRoomDeviceListResultBean.FamilyDevice) item).getDeviceId() == deviceId) {
                        ((GetRoomDeviceListResultBean.FamilyDevice) item).setAlarmContent(event.getAlarmContent());
                        ((GetRoomDeviceListResultBean.FamilyDevice) item).setAlarmFlag(event.getAlarmFlag());
                        mContentAdapter.notifyItemChanged(i);
                        break;
                    }
                }
            }

            for (int i = 0; i < mCommonDatas.size(); i++) {
                Object item = mCommonDatas.get(i);
                if (item instanceof GetRoomDeviceListResultBean.FamilyDevice) {
                    if (((GetRoomDeviceListResultBean.FamilyDevice) item).getDeviceId() == deviceId) {
                        ((GetRoomDeviceListResultBean.FamilyDevice) item).setAlarmContent(event.getAlarmContent());
                        ((GetRoomDeviceListResultBean.FamilyDevice) item).setAlarmFlag(event.getAlarmFlag());
                        mCommonAdapter.notifyItemChanged(i);
                        break;
                    }
                }
            }
        }
    }

    @Override
    protected void initView() {
        initContentView();
        initRoomView();
        initSceneView();
        initCommonView();
    }

    @Override
    protected void initDatas() {
        if (App.getInstance().checkLoginAndStartLoginActivity(mContext)) {
            mPresenter.getHomeList();
            mPresenter.getWeatherByIp();
        }
    }

    @Override
    protected void initEvent() {
        RxView.clicks(mBinding.llMenuOne)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showHomeListPopupWindow();
                    }
                });
        RxView.clicks(mBinding.llMenuTwo)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        SettingActivity.startActivity(mContext);
                    }
                });
    }

    private void showHomeListPopupWindow() {
        if (mHomelistPopupWindow == null) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            PopupHomeListBinding popupHomeListBinding = DataBindingUtil.inflate(inflater, R.layout.popup_home_list, null, false);
            mHomelistPopupWindow = new EasyPopup(this)
                    .setContentView(popupHomeListBinding.getRoot())
                    .setFocusAndOutsideEnable(true)
                    .createPopup();
            //init recycler view
            Items datas = new Items();
            datas.addAll(mHomeListDatas);
            MultiTypeAdapter adapter = new MultiTypeAdapter();
            adapter.register(GetHomeListResultBean.SmartHomeListBean.class, new HomeListItemViewBinder(mContext, this));
            popupHomeListBinding.recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
            RecyclerViewDivider.with(mContext)
                    .color(getResources().getColor(R.color.color_line_home_popup))
                    .size(ScreenUtils.dp2px(mContext, 1))
                    .hideLastDivider()
                    .build()
                    .addTo(popupHomeListBinding.recyclerview);
            popupHomeListBinding.recyclerview.setItemAnimator(new DefaultItemAnimator());
            adapter.setItems(datas);
            popupHomeListBinding.recyclerview.setAdapter(adapter);
        }
        mHomelistPopupWindow.showAtAnchorView(mBinding.llMenuOne, VerticalGravity.BELOW, HorizontalGravity.CENTER);
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onHomeListLoaded(GetHomeListResultBean datas) {
        if (datas != null && datas.getSmartHomeList() != null && datas.getSmartHomeList().size() > 0) {
            mHomeListDatas = datas.getSmartHomeList();
            onHomeItemSelected(mHomeListDatas.get(0));
        }
    }

    @Override
    public void onRoomListLoaded(GetRoomListResultBean datas) {
        mRoomDatas.clear();
        mRoomDatas.add(new GetRoomListResultBean.SmartRoomListBean(-1, getString(R.string.home_common_device), ""));
        if (datas != null && datas.getSmartRoomList() != null && datas.getSmartRoomList().size() > 0) {
            mRoomDatas.addAll(datas.getSmartRoomList());
        }
        mRoomDatas.add(new GetRoomListResultBean.SmartRoomListBean(0, getString(R.string.home_default_room), ""));
        mRoomAdapter.notifyDataSetChanged();
        onRoomItemSelected((GetRoomListResultBean.SmartRoomListBean) mRoomDatas.get(0));
    }

    @Override
    public void onWeatherLoaded(GetWeatherByIpResultBean datas) {
        if (datas != null && datas.getWeather() != null && datas.getWeather().getResult() != null && datas.getWeather().getResult().size() > 0) {
            GetWeatherByIpResultBean.WeatherBean.ResultBean resultBean = datas.getWeather().getResult().get(0);
            mBinding.weatherLayout.tvTemperature.setText(resultBean.getTemperature() == null ? "" : resultBean.getTemperature().replace("℃", ""));
            mBinding.weatherLayout.tvWeather.setText(resultBean.getWeather() + "(实时)");
            mBinding.weatherLayout.tvAirCondition.setText(resultBean.getAirCondition());
            mBinding.weatherLayout.tvHumidity.setText(resultBean.getHumidity() == null ? "" : resultBean.getHumidity().replace("湿度：", ""));
        }
    }

    @Override
    public void onRoomDeviceListLoaded(GetRoomDeviceListResultBean datas) {
        mBinding.tvCurrentRoomName.setText(mCurrentRoomName);
        if (datas != null && datas.getRoomDeviceList() != null) {
            mContentDatas.clear();
            mContentDatas.addAll(datas.getRoomDeviceList());
            mContentAdapter.notifyDataSetChanged();
            mBinding.tvCurrentRoomDeviceSize.setText("(" + datas.getRoomDeviceList().size() + "个设备)");
        }
    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public void onHomeItemSelected(GetHomeListResultBean.SmartHomeListBean smartHomeListBean) {
        if (smartHomeListBean != null) {
            mRoomDatas.clear();
            mRoomAdapter.notifyDataSetChanged();
            String homeName = "";
            if (TextUtils.isEmpty(smartHomeListBean.getHomeName())) {
                homeName = "我的家庭";
            } else {
                homeName = smartHomeListBean.getHomeName();
            }
            mBinding.tvMenuOne.setText(homeName);
            mPresenter.getRoomList(smartHomeListBean.getHomeId());
            mCurrentHomeId = smartHomeListBean.getHomeId();
        }
        if (mHomelistPopupWindow != null) {
            mHomelistPopupWindow.dismiss();
        }
    }

    @Override
    public void onRoomItemSelected(GetRoomListResultBean.SmartRoomListBean smartRoomListBean) {
        if (smartRoomListBean != null) {
            if (smartRoomListBean.getRoomId() == -1) {//常用设备
                mBinding.llCommonDevice.setVisibility(View.VISIBLE);
                mBinding.llRoomDevice.setVisibility(View.GONE);
                mCommonDatas.clear();
                mCommonAdapter.notifyDataSetChanged();
                mTaskDatas.clear();
                mSceneAdapter.notifyDataSetChanged();
                mPresenter.getSceneList(mCurrentHomeId);
                mPresenter.getCommonDeviceList(mCurrentHomeId);
            } else {
                mBinding.llCommonDevice.setVisibility(View.GONE);
                mBinding.llRoomDevice.setVisibility(View.VISIBLE);
                mContentDatas.clear();
                mContentAdapter.notifyDataSetChanged();
                mCurrentRoomName = smartRoomListBean.getRoomName();
                mPresenter.getRoomDeviceList(mCurrentHomeId, smartRoomListBean.getRoomId());
            }
        }
    }

    @Override
    public void onTimeChanged() {
        try {
            DateTimeModel dateTimeModel = DateTimeUtils.parseDateTimeToModel(System.currentTimeMillis());
            String hour = dateTimeModel.getHour() > 9 ? ("" + dateTimeModel.getHour()) : ("0" + dateTimeModel.getHour());
            String minute = dateTimeModel.getMinute() > 9 ? ("" + dateTimeModel.getMinute()) : ("0" + dateTimeModel.getMinute());
            String month = dateTimeModel.getMonth() > 9 ? ("" + dateTimeModel.getMonth()) : ("0" + dateTimeModel.getMonth());
            String day = dateTimeModel.getDay() > 9 ? ("" + dateTimeModel.getDay()) : ("0" + dateTimeModel.getDay());
            mBinding.weatherLayout.tvTime.setText(hour + ":" + minute);
            mBinding.weatherLayout.tvDate.setText(dateTimeModel.getYear() + "-" + month + "-" + day + " " + DateTimeUtils.getWeekByIndex(dateTimeModel.getWeek()));
        } catch (Exception e) {

        }
    }

    @Override
    public void onTaskListLoaded(GetTaskListResultBean datas) {
        if (datas != null && datas.getSmartTaskList() != null) {
            mTaskDatas.clear();
            mTaskDatas.addAll(datas.getSmartTaskList());
            mSceneAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onCommonDeviceListLoaded(GetRoomDeviceListResultBean datas) {
        if (datas != null && datas.getRoomDeviceList() != null) {
            mCommonDatas.clear();
            mCommonDatas.addAll(datas.getRoomDeviceList());
            mCommonAdapter.notifyDataSetChanged();
            mBinding.tvCurrentRoomDeviceSizeCommon.setText("(" + datas.getRoomDeviceList().size() + "个设备)");
        }
    }

    //------------------content recyclerview start========================
    private void initContentView() {
        GridLayoutManager layoutManage = new GridLayoutManager(mContext, 4);
        mBinding.recyclerviewContent.setLayoutManager(layoutManage);

        int itemSpace = getResources().
                getDimensionPixelSize(R.dimen.home_content_recyclerView_item_space);
        mBinding.recyclerviewContent.addItemDecoration(new SpaceItemDecoration(itemSpace));
        mContentAdapter = new MultiTypeAdapter();
        mContentAdapter.register(GetRoomDeviceListResultBean.FamilyDevice.class, new ContentListtemViewBinder(mContext, this));
        mContentAdapter.setItems(mContentDatas);
        mBinding.recyclerviewContent.setAdapter(mContentAdapter);
    }

    private class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                                   RecyclerView.State state) {
            outRect.bottom = space;
            outRect.left = space;
        }
    }


    public void onDeviceClicked(int position) {
        if (mContentDatas.size() > position) {

            GetRoomDeviceListResultBean.FamilyDevice familyDevice = (GetRoomDeviceListResultBean.FamilyDevice) mContentDatas.get(position);
            if (familyDevice != null) {
                mPresenter.onDeviceClicked(familyDevice, mCurrentRoomName);
            }
        }
    }
    //------------------content recyclerview end========================

    //------------------room recyclerview start========================

    private void initRoomView() {
        mRoomAdapter = new MultiTypeAdapter();
        mRoomAdapter.register(GetRoomListResultBean.SmartRoomListBean.class, new RoomListtemViewBinder(mContext, this));
        mBinding.recyclerviewRoom.setLayoutManager(new LinearLayoutManager(mContext));
        mBinding.recyclerviewRoom.setItemAnimator(new DefaultItemAnimator());
        mRoomAdapter.setItems(mRoomDatas);
        mBinding.recyclerviewRoom.setAdapter(mRoomAdapter);
    }
    //------------------room recyclerview end========================

    //------------------场景 recyclerview start========================

    private void initSceneView() {
        mSceneAdapter = new MultiTypeAdapter();
        mSceneAdapter.register(GetTaskListResultBean.SmartTaskListBean.class, new TaskListtemViewBinder(mContext, this));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mBinding.recyclerviewScene.setLayoutManager(linearLayoutManager);
        mBinding.recyclerviewScene.setItemAnimator(new DefaultItemAnimator());
        mSceneAdapter.setItems(mTaskDatas);
        mBinding.recyclerviewScene.setAdapter(mSceneAdapter);
    }

    //------------------场景 recyclerview end========================

    //------------------常用设备 recyclerview start========================

    private void initCommonView() {
        GridLayoutManager layoutManage = new GridLayoutManager(mContext, 4);
        mBinding.recyclerviewContentCommon.setLayoutManager(layoutManage);

        int itemSpace = getResources().
                getDimensionPixelSize(R.dimen.home_content_recyclerView_item_space);
        mBinding.recyclerviewContentCommon.addItemDecoration(new SpaceItemDecoration(itemSpace));
        mCommonAdapter = new MultiTypeAdapter();
        mCommonAdapter.register(GetRoomDeviceListResultBean.FamilyDevice.class, new ContentListtemViewBinder(mContext, this));
        mCommonAdapter.setItems(mCommonDatas);
        mBinding.recyclerviewContentCommon.setAdapter(mCommonAdapter);
    }

    //------------------常用设备 recyclerview end========================

}
